
import math,resource,time
INF = 10e10

from torch import nn
import torch,math,random,os
import collections
import torch.nn.functional as F
import numpy as np

class ReplayBuffer:
    ''' 经验回放池 '''
    def __init__(self, capacity):
        self.buffer = collections.deque(maxlen=capacity)  # 队列,先进先出

    def add(self, state, action, reward, next_state):  # 将数据加入buffer
        self.buffer.append((state, action, reward, next_state))

    def sample(self, batch_size):  # 从buffer中采样数据,数量为batch_size
        transitions = random.sample(self.buffer, batch_size)
        state, action, reward, next_state = zip(*transitions)
        return np.array(state), action, reward, np.array(next_state)

    def size(self):  # 目前buffer中数据的数量
        return len(self.buffer)

class Qnet(torch.nn.Module):
    ''' 只有一层隐藏层的Q网络 '''
    def __init__(self, state_dim, hidden_dim, action_dim):
        super(Qnet, self).__init__()
        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
        self.fc2 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.fc3 = torch.nn.Linear(hidden_dim, action_dim)

    def forward(self, x):
        x = F.relu(self.fc1(x))  # 隐藏层使用ReLU激活函数
        x = F.relu(self.fc2(x))
        return self.fc3(x)

class DQN:
    ''' DQN算法 '''
    def __init__(self, state_dim, hidden_dim, action_dim, learning_rate, gamma,
                 epsilon, target_update, device):
        self.action_dim = action_dim
        self.q_net = Qnet(state_dim, hidden_dim,
                          self.action_dim).to(device)  # Q网络
        # 目标网络
        self.target_q_net = Qnet(state_dim, hidden_dim,
                                 self.action_dim).to(device)
        # 使用Adam优化器
        self.optimizer = torch.optim.Adam(self.q_net.parameters(),
                                          lr=learning_rate)
        self.gamma = gamma  # 折扣因子
        self.epsilon = epsilon  # epsilon-贪婪策略
        self.target_update = target_update  # 目标网络更新频率
        self.count = 0  # 计数器,记录更新次数
        self.device = device

    def take_action(self, state):  # epsilon-贪婪策略采取动作
        if np.random.random() < self.epsilon:
            action = np.random.randint(self.action_dim)
        else:
            state = torch.tensor([state], dtype=torch.float).to(self.device)
            action = self.q_net(state).argmax().item()
        return action

    def update(self, transition_dict):
        states = torch.tensor(transition_dict['states'],dtype=torch.float).to(self.device)
        actions = torch.tensor(transition_dict['actions']).view(-1, 1).to(self.device)
        rewards = torch.tensor(transition_dict['rewards'],dtype=torch.float).view(-1, 1).to(self.device)
        next_states = torch.tensor(transition_dict['next_states'],dtype=torch.float).to(self.device)
#         dones = torch.tensor(transition_dict['dones'],
#                              dtype=torch.float).view(-1, 1).to(self.device)

        q_values = self.q_net(states).gather(1, actions)  # Q值
        # 下个状态的最大Q值
        max_next_q_values = self.target_q_net(next_states).max(1)[0].view(-1, 1)
        q_targets = rewards + self.gamma * max_next_q_values # TD误差目标
        dqn_loss = torch.mean(F.mse_loss(q_values, q_targets))  # 均方误差损失函数
        self.optimizer.zero_grad()  # PyTorch中默认梯度会累积,这里需要显式将梯度置为0
        dqn_loss.backward()  # 反向传播更新参数
        self.optimizer.step()

        if self.count % self.target_update == 0:
            self.target_q_net.load_state_dict(
                self.q_net.state_dict())  # 更新目标网络
        self.count += 1


def length(worker:list,task:list)->float:#求两个点的长度
    distance = (worker[2]-task[2])**2+(worker[3]-task[2])**2
#     print(distance)
    distance = pow(distance,1/2)
    return distance
#     print(distance)

def length2(worker:list,task:list)->float:#求两个点的长度,不开方的
    distance = (worker[2]-task[2])**2+(worker[3]-task[3])**2
    return distance

def satisfyLoc(worker:list,task:list)->bool:#验证任务与工作者之间是否符合活动范围内
    if length2(worker,task) > worker[4]*worker[4]:
        return False
    return True

def satifyTime(worker:list,task:list)->bool:
    if (worker[0] < task[4] and task[0] < worker[6]) is False:
        return False
    return True

def satify(worker:list,task:list)->bool:
    if satifyTime(worker,task) and satisfyLoc(worker,task):
        return True
    return False
    

def calcCost(worker:list,task:list)->float:
    if satisfyLoc(worker,task) and satifyTime(worker,task):
        return worker[7]*task[5]
    else:
        return 0.0

def dcmp(a:float,b:float)->bool:
    return math.isclose(a,b,rel_tol=1e-6)
def dcmp(a:float)->bool:
    return abs(a)<1e-6

class KM:
    def __init__(self,curTime,workerlist,tasklist):
        self.curTime = curTime
        self.workerlist = workerlist
        self.tasklist = tasklist
        self.wsize = len(workerlist)
        self.tsize = len(tasklist)
        self.slack = INF
        self.slacks = []
        self.weight = []
        self.lx = []
        self.ly = []
        self.xy = []
        self.yx = []
        self.visitx = []
        self.visity = []
        
        
    def build(self,flag):
        if flag:#一般情况需要左边的节点少于右边节点，因为我选择右边节点开始遍历，如果右边节点多余左边节点会出现完全匹配时候无法退出dfs
            self.lx = [0.0 for i in range(self.wsize)]
            self.ly = [0.0 for i in range(self.tsize)]
            self.xy = [-1 for i in range(self.wsize)]
            self.yx = [-1 for i in range(self.tsize)]
            self.visitx = [False for i in range(self.wsize)]
            self.visity = [False for i in range(self.tsize)]
            for x in range(self.wsize):
                temp = []
                for y in range(self.tsize):
                    u = calcCost(self.workerlist[x],self.tasklist[y])
                    temp.append(u)
                    self.lx[x] = max(u,self.lx[x])
                self.weight.append(temp)
                    
        else:
            self.lx = [0.0 for i in range(self.tsize)]
            self.ly = [0.0 for i in range(self.wsize)]
            self.xy = [-1 for i in range(self.tsize)]
            self.yx = [-1 for i in range(self.wsize)]
            self.visitx = [False for i in range(self.tsize)]
            self.visity = [False for i in range(self.wsize)]
            for x in range(self.tsize):
                temp = []
                for y in range(self.wsize):
                    u = calcCost(self.workerlist[y],self.tasklist[x])
                    temp.append(u)
                    self.lx[x] = max(u,self.lx[x])
                self.weight.append(temp)
      
    def success(self,flag):
        #识别并删除成功匹配的
        utility = 0.0
        matchNum = 0
        removeWorkers = [False for i in range(self.wsize)]
        removeTasks = [False for i in range(self.tsize)]
        if flag:
            for w,t in enumerate(self.xy):
                if t!=-1:
                    u = self.weight[w][t]
                    # u1 = calcCost(self.workerlist[w],self.tasklist[t])
                    # if u!=u1:
                    #     print(u,u1)
                    if u > 0.0:#匹配成功
                        utility +=u
                        removeWorkers[w]=True
                        removeTasks[t]=True
                        matchNum += 1
        else:
            for t,w in enumerate(self.xy):
                if w!=-1:
                    u = self.weight[t][w]
#                     u1 = calcCost(self.workerlist[w],self.tasklist[t])
#                     if u!=u1:
#                         print(u,u1)
                    if u > 0.0:
                        utility +=u
                        removeWorkers[w]=True
                        removeTasks[t]=True
                        matchNum += 1
        #识别未匹配成功的，并删除超时的众包对象
        wt = []
        tt = []
        for w,flag in enumerate(removeWorkers):
            worker = self.workerlist[w]
            if flag==False and worker[6] >= self.curTime:
#             if flag==False:
                wt.append(worker)
        
        for t,flag in enumerate(removeTasks):
            task = self.tasklist[t]
            if flag==False and task[4] >= self.curTime:
#             if flag==False:
                tt.append(task)

        return [utility,wt,tt,matchNum]
    
    def dfs(self,x:int)->bool:
        self.visitx[x] = True
        for y,flag in enumerate(self.visity):
            if flag:
                continue
            temp = self.lx[x] + self.ly[y] - self.weight[x][y]
#             temp = self.lx[x] + self.ly[y] - calcCost(self.workerlist[x],self.tasklist[y])
            if dcmp(temp):
                self.visity[y] = True
                if self.yx[y] == -1 or self.dfs(self.yx[y]):
                    self.xy[x] = y
                    self.yx[y] = x
                    return True
            else:
                self.slack = min(self.slack,temp)
                self.slacks[y] = min(self.slacks[y],temp)###
        return False 
    
    def match(self):
        ans = [0,[],[],0]
        wtflag = False
        
        if self.wsize <= self.tsize:#工作者作为左边节点
            if self.wsize == 0 or self.tsize == 0:
                ans[1] = self.workerlist
                ans[2] = self.tasklist
                return ans
            wtflag = True
            self.build(wtflag)
            for x in range(self.wsize): 
                self.slacks = [INF for i in range(self.tsize)]###
                while True:
                    self.visitx = [False for i in range(self.wsize)]
                    self.visity = [False for i in range(self.tsize)]
                    self.slack = INF
                    #wsize<tsize
                    if self.dfs(x):
                        break

                    #更新访问过的节点, 因为self.wsize <= self.tsize，这里还可以优化加速
                    mm = INF###
                    for i,flag in enumerate(self.visity):###
                        if flag == False:###
                            mm = min(self.slacks[i],mm)###
                    for i,flag in enumerate(self.visitx):
                        if flag:
                            self.lx[i] -= self.slack
#                             self.lx[i] -= mm###
                    for i,flag in enumerate(self.visity):
                        if flag:
                            self.ly[i] += self.slack
#                             self.ly[i] += mm###
                        else:###
                            self.slacks[i] -= mm###
            ans = self.success(wtflag)#工作者左边
            return ans

        else:#任务作为左边节点
            if self.wsize == 0 or self.tsize == 0:
                ans[1] = self.workerlist
                ans[2] = self.tasklist
                return ans
            wtflag = False
            self.build(wtflag)
            for x in range(self.tsize):
                self.slacks = [INF for i in range(self.wsize)]###
                while True:
                    self.visitx = [False for i in range(self.tsize)]
                    self.visity = [False for i in range(self.wsize)]
                    self.slack = INF
                    if self.dfs(x):
                        break
                    #更新访问过的节点, 因为self.wsize > self.tsize，这里还可以优化加速
                    mm = INF###
                    for i,flag in enumerate(self.visity):###
                        if flag == False:###
                            mm = min(self.slacks[i],mm)###
                            
                    for i,flag in enumerate(self.visitx):
                        if flag:
                            self.lx[i] -= self.slack
#                             self.lx[i] -= mm###
                    for i,flag in enumerate(self.visity):
                        if flag:
                            self.ly[i] += self.slack
#                             self.ly[i] += mm###
                        else:###
                            self.slacks[i] -= mm###
            ans = self.success(wtflag)#任务左边
            return ans
workers = []
tasks = []
queue = []
#读取文件数据
def readData(fileName):
    with open(fileName,'r') as f:
        data = f.readlines()
        first = data[0].strip("\n").split(" ")
        workerNum = int(first[0])
        taskNum = int(first[1])
        for i in range(1,len(data)):
            node = data[i].strip("\n").split(" ")
            if node[1]=='w':
                node[0]=int(node[0])#到达时间
                node[2]=float(node[2])#纬度
                node[3]=float(node[3])#经度
                node[4]=float(node[4])#半径
                node[5]=int(node[5])#能力
                node[6]=int(node[6])+node[0]#停留的时间
                node[7]=float(node[7])#接受率
                if len(node) < 9:#最后一个用来记录等待多久匹配
                    node.append(0)
                else:
                    node[8] = 0
                workers.append(node)
            else:
                node[0]=int(node[0])#到达时间
                node[2]=float(node[2])#纬度
                node[3]=float(node[3])#经度
                node[4]=int(node[4])+node[0]#停留的时间
                node[5]=float(node[5])#支付的报酬
                if len(node) < 7:
                    node.append(0)
                else:
                    node[6] = 0
                tasks.append(node)
            queue.append(node)
    return workerNum,taskNum

#用于识别当前时刻可以有多少匹配的任务和工作者
def matchWT(pworkers:list,ptasks:list,wmatch:list,tmatch:list):
    wn = []
    tn = []
    for item in pworkers:
        if item[8] > 0:
            item[8] -= 1
            wn.append(item)
        else:
            wmatch.append(item)
    for item in ptasks:
        if item[6] > 0:
            item[6] -= 1
            tn.append(item)
        else:
            tmatch.append(item)
    return wn,tn
#从队列中移除超时的
def removeDeadline(curTime:int,wmatch:list,tmatch:list):
    ww = []
    tt = []
    for w in wmatch:
        if w[6] >= curTime:
            ww.append(w)
    for t in tmatch:
        if t[4] >= curTime:
            tt.append(t)
    return ww,tt

def DeepQleanring():
    utility = 0.0
    matchNum = 0
     #DQN的参数
    gamma = 0.98
    epsilon = 0.01 #用于e-贪婪策略选择动作
    lr = 2e-3 #深度学习的学习率
    target_update = 10
    buffer_size = 10000
    minimal_size = 500
    batch_size = 64
    state_dim = 7#状态维度
    action_dim = 6#动作维度
    hidden_dim = 128
    state = [0,0,0,0,0,0,0]
    nextState = [0,0,0,0,0,0,0]
    lastTime = -1
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device(
        "cpu")
    torch.manual_seed(0)
    replay_buffer = ReplayBuffer(buffer_size)
    agent = DQN(state_dim, hidden_dim, action_dim, lr, gamma, epsilon,target_update, device)
    
    #交互环境
    wlx = []
    tly = []
    arriveWorkers = []
    arriveTasks = []
    wmatch = []
    tmatch = []
    reward = 0
    for i in range(action_dim):
        wlx.append([])
        tly.append([])

    for item in queue:
        arriveTime = item[0]
        objtype = item[1]
        if objtype == 'w':#工作者到
#             item[8] = action#等待时间
            cap = item[5]
            for i in range(cap):#能力分解为多个为1的工作者
                arriveWorkers.append(item) 
        else:#任务到
#             item[6] = action
            arriveTasks.append(item)
            
        if lastTime != arriveTime:
            action = agent.take_action(state)#采取动作
            waiteTime = (arriveTime+action)%action_dim
            wlx[waiteTime].extend(arriveWorkers)
            tly[waiteTime].extend(arriveTasks)
            wmatch.extend(wlx[arriveTime%action_dim])
            tmatch.extend(tly[arriveTime%action_dim])
            wlx[arriveTime%action_dim] = []
            tly[arriveTime%action_dim] = []
            #进行匹配
            assignment = KM(arriveTime,wmatch,tmatch)
            reward,wmatch,tmatch,ntemp = assignment.match()
            utility += reward
            matchNum += ntemp
            nextState[0] = arriveTime
            wnu = len(wmatch)
            tnu = len(tmatch)
            for ws in wlx:
                wnu += len(ws)
            for ts in tly:
                tnu += len(ts)
            nextState[1] = wnu
            nextState[2] = tnu
            arriveWorkers.clear()
            arriveTasks.clear()
            lastTime = arriveTime
            #进行训练
            replay_buffer.add(state, action, reward, nextState)
            state = nextState
            if replay_buffer.size() > minimal_size:
                b_s, b_a, b_r, b_ns = replay_buffer.sample(batch_size)
                transition_dict = {
                    'states': b_s,
                    'actions': b_a,
                    'next_states': b_ns,
                    'rewards': b_r
                }
                agent.update(transition_dict)
             
    return utility,matchNum

def solve():
    memory = resource.getrusage(resource.RUSAGE_SELF)
    avgUtility = 0.0
    avgTime = 0
    avgMemory = 0
    avgMatchNu = 0
    startTime = time.perf_counter()
    avgUtility,avgMatchNu = DeepQleanring()
    endTime = time.perf_counter()
    avgTime = endTime - startTime
    avgMemory = memory.ru_maxrss
    # print(avgUtility,avgTime,avgMemory,avgMatchNu)
    return [avgUtility,avgTime,avgMemory,avgMatchNu]


def varyWorkers(testNUm):#测试变化的工作者，其余变量保持不变
    fin = open("./result/synthetic/data/varyworkers.txt",'a+',encoding='utf-8')
    for w in  [100, 200, 500, 1000, 5000]:
        fileName = f"./dataset/synthetic/{w}_2500_1_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyTasks(testNUm):#测试变化的工作者
    fin = open("./result/synthetic/data/varytasks.txt",'a+',encoding='utf-8')
    for t in   [500, 1000, 2500, 5000, 10000]:
        fileName = f"./dataset/synthetic/500_{t}_1_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyCw(testNUm):#测试工作者能力变化的影响
    fin = open("./result/synthetic/data/varycw.txt",'a+',encoding='utf-8')
    for cw in [1, 2, 3, 4, 5]:
        fileName = f"./dataset/synthetic/500_2500_{cw}_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyRw(testNUm):#测试工作者半径变化的影响
    fin = open("./result/synthetic/data/varyrw.txt",'a+',encoding='utf-8')
    for rw in [1.0, 1.5, 2.0, 2.5, 3.0]:
        fileName = f"./dataset/synthetic/500_2500_1_{rw}_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyDw(testNUm):#工作者接受率变化的影响
    fin = open("./result/synthetic/data/varydw.txt",'a+',encoding='utf-8')
    for dw in [0.1, 0.3, 0.5, 0.7, 0.9]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_{dw}_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyDdl(testNUm):#截至时间变化的影响
    fin = open("./result/synthetic/data/varyddl.txt",'a+',encoding='utf-8')
    for ddl in [2, 4, 6, 8, 10]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_{ddl}_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsNormal(testNUm):#正态分布任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsnormal.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsExponentail(testNUm):#指数分布任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsexponentail.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt+100}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsUniform(testNUm):#任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsuniform.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt+1000}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def scalability(testNUm):
    fin = open("./result/synthetic/data/scalability.txt",'a+',encoding='utf-8')
    for s in range(1,11):
        w = s*10**3
        t = s*10**4
        fileName = f"./dataset/synthetic/{w}_{t}_1_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def EverySenderCw(testNUm):#真实数据集
    fin = open("./result/real/data/varyEverysenderCw.txt",'a+',encoding='utf-8')
    for cap in [1,2,3,4,5,6,7,8,9,10]:
        fileName = f"./dataset/real/EverySender_cap{cap}/data_00_time.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            workers.clear()
            tasks.clear()
            queue.clear()
            readData(fileName)
            for n in range(testNUm):#测试次数
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "DQL(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
    fin.close()

def  gMissionCw(testNUm):
        fin = open("./result/real/data/varygMissionCw.txt",'a+',encoding='utf-8')
        for cap in [1,2,3,4,5,6,7,8,9,10]:
            fileName = f"./dataset/real/gMission_cap{cap}/data_00_time.txt"
            ansList = [0,0,0,0]
            if os.path.exists(fileName):
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                for n in range(testNUm):#测试次数
                    ans=solve()
                    for ansi in range(4):
                        ansList[ansi] += ans[ansi]
                writeStr = "DQL(ours)"
                for result in ansList:
                    temp = result/testNUm
                    print(temp,end=' ')
                    writeStr +=" "+str(temp)
                print()
                writeStr += "\n"
                fin.write(writeStr)
            else:
                print(fileName,"文件不存在")
        fin.close()


if __name__ =="__main__":
    testNum = 10
    varyWorkers(testNum)
    varyTasks(testNum)
    varyCw(testNum)
    varyRw(testNum)
    varyDw(testNum)
    varyDdl(testNum)

    varyPtsNormal(testNum)
    varyPtsExponentail(testNum)
    varyPtsUniform(testNum)
    scalability(testNum)
    EverySenderCw(testNum)
    gMissionCw(testNum)